from collections.abc import Iterable


class MyNumbers:

    def __init__(self, numbers):
        self.numbers = numbers

    """
        实现了这个就是一个可迭代对象了
    """

    # def __iter__(self):
    #     # 必须返回一个迭代器
    #     return iter(self.numbers)

    def __iter__(self):
        """迭代器是一个一次性获取的数据，一次for循环后就不会再产生数据
        这里返回一个迭代器就可以不断获取数据了"""
        return MyNumbersIterator(self.numbers)


class MyNumbersIterator:

    def __init__(self, numbers):
        self.numbers = numbers
        self.index = 0

    """
        实现了这个就是一个可迭代对象了
    """

    def __iter__(self):
        # 必须返回一个迭代器
        return self

    """
        同时实现__iter__和__next__方法，那么就是一个迭代器
    """

    def __next__(self):
        try:
            number = self.numbers[self.index]
            self.index += 1
        except IndexError:
            raise StopIteration
        return number


a_list = [1, 2, 3, 4, 5]
my_numbers = MyNumbers(a_list)
# 判断是否是一个可迭代对象
print(isinstance(my_numbers, Iterable))

my_numbers_iterator = MyNumbersIterator(a_list)
print(next(my_numbers_iterator))
print(next(my_numbers_iterator))
print(next(my_numbers_iterator))
print(next(my_numbers_iterator))
print(next(my_numbers_iterator))
for i in my_numbers_iterator:
    print(i)